/*
 * Pythonforc - A lightweight Python interpreter in C
 * Copyright (C) 2025 Pythonforc Developers
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "Pythonforc.h"
#include <setjmp.h>
#include <ctype.h>
#include <math.h>
#include <dirent.h>
#include <sys/stat.h>
#include <time.h>
#include <stdarg.h>

struct py_frame;
/* 全局虚拟机实例 */
static py_vm* current_vm = NULL;

/* 内存管理 */
static void* py_malloc(size_t size) {
    void* ptr = malloc(size);
    if (!ptr) {
        fprintf(stderr, "Pythonforc: Out of memory\n");
        exit(1);
    }
    return ptr;
}

static void* py_realloc(void* ptr, size_t size) {
    ptr = realloc(ptr, size);
    if (!ptr && size > 0) {
        fprintf(stderr, "Pythonforc: Out of memory\n");
        exit(1);
    }
    return ptr;
}

static void py_free(void* ptr) {
    free(ptr);
}

/* 哈希函数 */
static size_t py_object_hash(py_object* obj) {
    if (!obj) return 0;
    
    switch (obj->type) {
        case PY_TYPE_INT:
            return (size_t)((py_int_object*)obj)->value;
        case PY_TYPE_FLOAT: {
            py_float value = ((py_float_object*)obj)->value;
            return (size_t)(*(int64_t*)&value);
        }
        case PY_TYPE_STRING: {
            py_string_object* str_obj = (py_string_object*)obj;
            size_t hash = 5381;
            for (size_t i = 0; i < str_obj->length; i++) {
                hash = ((hash << 5) + hash) + str_obj->value[i];
            }
            return hash;
        }
        case PY_TYPE_BOOL:
            return (size_t)(((py_bool_object*)obj)->value ? 1 : 0);
        case PY_TYPE_NONE:
            return 0;
        default:
            return (size_t)obj;
    }
}

/* 对象比较 */
static bool py_object_equal(py_object* a, py_object* b) {
    if (a == b) return true;
    if (!a || !b) return false;
    if (a->type != b->type) return false;
    
    switch (a->type) {
        case PY_TYPE_NONE:
            return true;
        case PY_TYPE_INT:
            return ((py_int_object*)a)->value == ((py_int_object*)b)->value;
        case PY_TYPE_FLOAT:
            return ((py_float_object*)a)->value == ((py_float_object*)b)->value;
        case PY_TYPE_BOOL:
            return ((py_bool_object*)a)->value == ((py_bool_object*)b)->value;
        case PY_TYPE_STRING: {
            py_string_object* str_a = (py_string_object*)a;
            py_string_object* str_b = (py_string_object*)b;
            if (str_a->length != str_b->length) return false;
            return memcmp(str_a->value, str_b->value, str_a->length) == 0;
        }
        case PY_TYPE_BYTES: {
            py_bytes_object* bytes_a = (py_bytes_object*)a;
            py_bytes_object* bytes_b = (py_bytes_object*)b;
            if (bytes_a->length != bytes_b->length) return false;
            return memcmp(bytes_a->value, bytes_b->value, bytes_a->length) == 0;
        }
        case PY_TYPE_LIST: {
            py_list_object* list_a = (py_list_object*)a;
            py_list_object* list_b = (py_list_object*)b;
            if (list_a->length != list_b->length) return false;
            for (size_t i = 0; i < list_a->length; i++) {
                if (!py_object_equal(list_a->items[i], list_b->items[i])) {
                    return false;
                }
            }
            return true;
        }
        case PY_TYPE_TUPLE: {
            py_tuple_object* tuple_a = (py_tuple_object*)a;
            py_tuple_object* tuple_b = (py_tuple_object*)b;
            if (tuple_a->length != tuple_b->length) return false;
            for (size_t i = 0; i < tuple_a->length; i++) {
                if (!py_object_equal(tuple_a->items[i], tuple_b->items[i])) {
                    return false;
                }
            }
            return true;
        }
        default:
            return a == b;
    }
}

/* 垃圾回收 */
static void py_gc_mark_object(py_object* obj){
    if (!obj || obj->ref_count & 0x80000000) {
        return;
    }
    
    obj->ref_count |= 0x80000000;
    
    switch (obj->type) {
        case PY_TYPE_LIST: {
            py_list_object* list = (py_list_object*)obj;
            for (size_t i = 0; i < list->length; i++) {
                py_gc_mark_object(list->items[i]);
            }
            break;
        }
        case PY_TYPE_TUPLE: {
            py_tuple_object* tuple = (py_tuple_object*)obj;
            for (size_t i = 0; i < tuple->length; i++) {
                py_gc_mark_object(tuple->items[i]);
            }
            break;
        }
        case PY_TYPE_DICT: {
            py_dict_object* dict = (py_dict_object*)obj;
            for (size_t i = 0; i < dict->capacity; i++) {
                dict_entry* entry = dict->buckets[i];
                while (entry) {
                    py_gc_mark_object(entry->key);
                    py_gc_mark_object(entry->value);
                    entry = entry->next;
                }
            }
            break;
        }
        case PY_TYPE_FUNCTION: {
            py_function_object* func = (py_function_object*)obj;
            py_gc_mark_object(func->globals);
            py_gc_mark_object((py_object*)func->code);
            break;
        }
        case PY_TYPE_MODULE: {
            py_module_object* module = (py_module_object*)obj;
            py_gc_mark_object((py_object*)module->dict);
            break;
        }
        case PY_TYPE_TYPE: {
            py_type_object* type = (py_type_object*)obj;
            py_gc_mark_object((py_object*)type->dict);
            break;
        }
        case PY_TYPE_EXCEPTION: {
            py_exception_object* exc = (py_exception_object*)obj;
            py_gc_mark_object(exc->value);
            break;
        }
        default:
            break;
    }
}

static void py_gc_sweep(py_vm* vm) {
    py_object** obj = &vm->gc_head;
    while (*obj) {
        if (((*obj)->ref_count & 0x80000000) != 0) {
            (*obj)->ref_count &= 0x7FFFFFFF;
            obj = &(*obj)->next;
        } else {
            py_object* unreachable = *obj;
            *obj = unreachable->next;
            
            switch (unreachable->type) {
                case PY_TYPE_STRING:
                    py_free(((py_string_object*)unreachable)->value);
                    break;
                case PY_TYPE_BYTES:
                    py_free(((py_bytes_object*)unreachable)->value);
                    break;
                case PY_TYPE_LIST:
                    py_free(((py_list_object*)unreachable)->items);
                    break;
                case PY_TYPE_TUPLE:
                    py_free(((py_tuple_object*)unreachable)->items);
                    break;
                case PY_TYPE_DICT: {
                    py_dict_object* dict = (py_dict_object*)unreachable;
                    for (size_t i = 0; i < dict->capacity; i++) {
                        dict_entry* entry = dict->buckets[i];
                        while (entry) {
                            dict_entry* next = entry->next;
                            py_object_decref(entry->key);
                            py_object_decref(entry->value);
                            py_free(entry);
                            entry = next;
                        }
                    }
                    py_free(dict->buckets);
                    break;
                }
                case PY_TYPE_FUNCTION: {
                    py_function_object* func = (py_function_object*)unreachable;
                    py_free(func->name);
                    break;
                }
                case PY_TYPE_NATIVE_FUNCTION:
                    py_free(((py_native_function_object*)unreachable)->name);
                    break;
                case PY_TYPE_MODULE: {
                    py_module_object* module = (py_module_object*)unreachable;
                    py_free(module->name);
                    break;
                }
                case PY_TYPE_TYPE: {
                    py_type_object* type = (py_type_object*)unreachable;
                    py_free(type->name);
                    break;
                }
                case PY_TYPE_EXCEPTION: {
                    py_exception_object* exc = (py_exception_object*)unreachable;
                    py_free(exc->name);
                    break;
                }
                default:
                    break;
            }
            
            py_free(unreachable);
            vm->gc_count--;
        }
    }
}

void py_gc_collect(py_vm* vm) {
    if (!vm->gc_enabled) {
        return;
    }
    
    /* 标记阶段 */
    py_frame* frame = vm->current_frame;
    while (frame) {
        for (int i = 0; i < frame->stack_pointer; i++) {
            py_gc_mark_object(frame->stack[i]);
        }
        for (int i = 0; i < frame->code->local_count; i++) {
            py_gc_mark_object(frame->locals[i]);
        }
        py_gc_mark_object(frame->globals);
        py_gc_mark_object(frame->builtins);
        py_gc_mark_object(frame->exception);
        py_gc_mark_object(frame->traceback);
        py_gc_mark_object((py_object*)frame->code);
        
        frame = (py_frame*)frame->previous;
    }
    
    py_gc_mark_object(vm->modules);
    py_gc_mark_object(vm->builtins);
    
    /* 清除阶段 */
    py_gc_sweep(vm);
}

void py_gc_enable(py_vm* vm, bool enable) {
    vm->gc_enabled = enable;
}

void py_gc_set_threshold(py_vm* vm, size_t threshold) {
    vm->gc_threshold = threshold;
}

/* 对象引用计数 */
void py_object_incref(py_object* obj) {
    if (obj) {
        obj->ref_count++;
    }
}

void py_object_decref(py_object* obj) {
    if (!obj) {
        return;
    }
    
    obj->ref_count--;
    if (obj->ref_count == 0) {
        /* 将对象添加到GC链表以便回收 */
        if (current_vm) {
            obj->next = current_vm->gc_head;
            current_vm->gc_head = obj;
            current_vm->gc_count++;
            
            if (current_vm->gc_count >= current_vm->gc_threshold) {
                py_gc_collect(current_vm);
            }
        } else {
            /* 没有VM实例，直接释放对象 */
            switch (obj->type) {
                case PY_TYPE_STRING:
                    py_free(((py_string_object*)obj)->value);
                    break;
                case PY_TYPE_BYTES:
                    py_free(((py_bytes_object*)obj)->value);
                    break;
                case PY_TYPE_LIST:
                    py_free(((py_list_object*)obj)->items);
                    break;
                case PY_TYPE_TUPLE:
                    py_free(((py_tuple_object*)obj)->items);
                    break;
                case PY_TYPE_DICT: {
                    py_dict_object* dict = (py_dict_object*)obj;
                    for (size_t i = 0; i < dict->capacity; i++) {
                        dict_entry* entry = dict->buckets[i];
                        while (entry) {
                            dict_entry* next = entry->next;
                            py_object_decref(entry->key);
                            py_object_decref(entry->value);
                            py_free(entry);
                            entry = next;
                        }
                    }
                    py_free(dict->buckets);
                    break;
                }
                case PY_TYPE_FUNCTION: {
                    py_function_object* func = (py_function_object*)obj;
                    py_free(func->name);
                    break;
                }
                case PY_TYPE_NATIVE_FUNCTION:
                    py_free(((py_native_function_object*)obj)->name);
                    break;
                case PY_TYPE_MODULE: {
                    py_module_object* module = (py_module_object*)obj;
                    py_free(module->name);
                    break;
                }
                case PY_TYPE_TYPE: {
                    py_type_object* type = (py_type_object*)obj;
                    py_free(type->name);
                    break;
                }
                case PY_TYPE_EXCEPTION: {
                    py_exception_object* exc = (py_exception_object*)obj;
                    py_free(exc->name);
                    break;
                }
                default:
                    break;
            }
            py_free(obj);
        }
    }
}

/* 对象创建函数 */
py_object* py_none_new(void) {
    static py_object none = { PY_TYPE_NONE, 1, NULL };
    return &none;
}

py_object* py_int_new(py_int value) {
    py_int_object* obj = (py_int_object*)py_malloc(sizeof(py_int_object));
    obj->obj.type = PY_TYPE_INT;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->value = value;
    return (py_object*)obj;
}

py_object* py_float_new(py_float value) {
    py_float_object* obj = (py_float_object*)py_malloc(sizeof(py_float_object));
    obj->obj.type = PY_TYPE_FLOAT;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->value = value;
    return (py_object*)obj;
}

py_object* py_bool_new(bool value) {
    static py_bool_object true_obj = { { PY_TYPE_BOOL, 1, NULL }, true };
    static py_bool_object false_obj = { { PY_TYPE_BOOL, 1, NULL }, false };
    return value ? (py_object*)&true_obj : (py_object*)&false_obj;
}

py_object* py_string_new(const char* value) {
    py_string_object* obj = (py_string_object*)py_malloc(sizeof(py_string_object));
    obj->obj.type = PY_TYPE_STRING;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->length = strlen(value);
    obj->value = (char*)py_malloc(obj->length + 1);
    strcpy(obj->value, value);
    return (py_object*)obj;
}

py_object* py_string_new_with_length(const char* value, size_t length) {
    py_string_object* obj = (py_string_object*)py_malloc(sizeof(py_string_object));
    obj->obj.type = PY_TYPE_STRING;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->length = length;
    obj->value = (char*)py_malloc(length + 1);
    memcpy(obj->value, value, length);
    obj->value[length] = '\0';
    return (py_object*)obj;
}

py_object* py_bytes_new(const py_byte* value, size_t length) {
    py_bytes_object* obj = (py_bytes_object*)py_malloc(sizeof(py_bytes_object));
    obj->obj.type = PY_TYPE_BYTES;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->length = length;
    obj->value = (py_byte*)py_malloc(length);
    memcpy(obj->value, value, length);
    return (py_object*)obj;
}

py_object* py_list_new(size_t capacity) {
    py_list_object* obj = (py_list_object*)py_malloc(sizeof(py_list_object));
    obj->obj.type = PY_TYPE_LIST;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->length = 0;
    obj->capacity = capacity > 0 ? capacity : 1;
    obj->items = (py_object**)py_malloc(sizeof(py_object*) * obj->capacity);
    memset(obj->items, 0, sizeof(py_object*) * obj->capacity);
    return (py_object*)obj;
}

py_object* py_tuple_new(size_t length) {
    py_tuple_object* obj = (py_tuple_object*)py_malloc(sizeof(py_tuple_object));
    obj->obj.type = PY_TYPE_TUPLE;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->length = length;
    obj->items = (py_object**)py_malloc(sizeof(py_object*) * length);
    memset(obj->items, 0, sizeof(py_object*) * length);
    return (py_object*)obj;
}

static size_t py_dict_next_size(size_t min_size) {
    size_t size = 8;
    while (size < min_size) {
        size <<= 1;
    }
    return size;
}

py_object* py_dict_new(size_t capacity) {
    py_dict_object* obj = (py_dict_object*)py_malloc(sizeof(py_dict_object));
    obj->obj.type = PY_TYPE_DICT;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->count = 0;
    obj->capacity = py_dict_next_size(capacity);
    obj->buckets = (dict_entry**)py_malloc(sizeof(dict_entry*) * obj->capacity);
    memset(obj->buckets, 0, sizeof(dict_entry*) * obj->capacity);
    return (py_object*)obj;
}

py_object* py_function_new(py_code_object* code, py_object* globals, const char* name) {
    py_function_object* obj = (py_function_object*)py_malloc(sizeof(py_function_object));
    obj->obj.type = PY_TYPE_FUNCTION;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->name = (char*)py_malloc(strlen(name) + 1);
    strcpy(obj->name, name);
    obj->globals = globals;
    py_object_incref(globals);
    obj->code = code;
    py_object_incref((py_object*)code);
    return (py_object*)obj;
}

py_object* py_native_function_new(py_native_function func, const char* name) {
    py_native_function_object* obj = (py_native_function_object*)py_malloc(sizeof(py_native_function_object));
    obj->obj.type = PY_TYPE_NATIVE_FUNCTION;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->function = func;
    obj->name = (char*)py_malloc(strlen(name) + 1);
    strcpy(obj->name, name);
    return (py_object*)obj;
}

py_object* py_module_new(const char* name) {
    py_module_object* obj = (py_module_object*)py_malloc(sizeof(py_module_object));
    obj->obj.type = PY_TYPE_MODULE;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->name = (char*)py_malloc(strlen(name) + 1);
    strcpy(obj->name, name);
    obj->dict = (py_dict_object*)py_dict_new(0);
    return (py_object*)obj;
}

py_object* py_type_new(const char* name, py_type base_type) {
    py_type_object* obj = (py_type_object*)py_malloc(sizeof(py_type_object));
    obj->obj.type = PY_TYPE_TYPE;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->name = (char*)py_malloc(strlen(name) + 1);
    strcpy(obj->name, name);
    obj->base_type = base_type;
    obj->dict = (py_dict_object*)py_dict_new(0);
    return (py_object*)obj;
}

py_object* py_exception_new(const char* name, py_object* value) {
    py_exception_object* obj = (py_exception_object*)py_malloc(sizeof(py_exception_object));
    obj->obj.type = PY_TYPE_EXCEPTION;
    obj->obj.ref_count = 1;
    obj->obj.next = NULL;
    obj->name = (char*)py_malloc(strlen(name) + 1);
    strcpy(obj->name, name);
    obj->value = value;
    py_object_incref(value);
    return (py_object*)obj;
}

/* 字典操作 */
static dict_entry* py_dict_find_entry(py_dict_object* dict, py_object* key) {
    size_t index = py_object_hash(key) % dict->capacity;
    dict_entry* entry = dict->buckets[index];
    while (entry) {
        if (py_object_equal(entry->key, key)) {
            return entry;
        }
        entry = entry->next;
    }
    return NULL;
}

void py_dict_set_item(py_dict_object* dict, py_object* key, py_object* value) {
    size_t index = py_object_hash(key) % dict->capacity;
    dict_entry* entry = dict->buckets[index];
    
    /* 检查键是否已存在 */
    while (entry) {
        if (py_object_equal(entry->key, key)) {
            py_object_decref(entry->value);
            entry->value = value;
            py_object_incref(value);
            return;
        }
        entry = entry->next;
    }
    
    /* 创建新条目 */
    entry = (dict_entry*)py_malloc(sizeof(dict_entry));
    entry->key = key;
    py_object_incref(key);
    entry->value = value;
    py_object_incref(value);
    entry->next = dict->buckets[index];
    dict->buckets[index] = entry;
    dict->count++;
    
    /* 检查是否需要扩容 */
    if (dict->count > dict->capacity * 0.75) {
        size_t new_capacity = dict->capacity * 2;
        dict_entry** new_buckets = (dict_entry**)py_malloc(sizeof(dict_entry*) * new_capacity);
        memset(new_buckets, 0, sizeof(dict_entry*) * new_capacity);
        
        /* 重新哈希所有条目 */
        for (size_t i = 0; i < dict->capacity; i++) {
            dict_entry* entry = dict->buckets[i];
            while (entry) {
                dict_entry* next = entry->next;
                size_t new_index = py_object_hash(entry->key) % new_capacity;
                entry->next = new_buckets[new_index];
                new_buckets[new_index] = entry;
                entry = next;
            }
        }
        
        py_free(dict->buckets);
        dict->buckets = new_buckets;
        dict->capacity = new_capacity;
    }
}

py_object* py_dict_get_item(py_dict_object* dict, py_object* key) {
    dict_entry* entry = py_dict_find_entry(dict, key);
    return entry ? entry->value : NULL;
}

void py_dict_del_item(py_dict_object* dict, py_object* key) {
    size_t index = py_object_hash(key) % dict->capacity;
    dict_entry** entry_ptr = &dict->buckets[index];
    
    while (*entry_ptr) {
        if (py_object_equal((*entry_ptr)->key, key)) {
            dict_entry* entry = *entry_ptr;
            *entry_ptr = entry->next;
            py_object_decref(entry->key);
            py_object_decref(entry->value);
            py_free(entry);
            dict->count--;
            return;
        }
        entry_ptr = &(*entry_ptr)->next;
    }
}

/* 列表操作 */
void py_list_append(py_list_object* list, py_object* item) {
    if (list->length >= list->capacity) {
        list->capacity = list->capacity * 2;
        list->items = (py_object**)py_realloc(list->items, sizeof(py_object*) * list->capacity);
    }
    list->items[list->length++] = item;
    py_object_incref(item);
}

py_object* py_list_get_item(py_list_object* list, size_t index) {
    if (index >= list->length) {
        return NULL;
    }
    return list->items[index];
}

void py_list_set_item(py_list_object* list, size_t index, py_object* item) {
    if (index >= list->length) {
        return;
    }
    py_object_decref(list->items[index]);
    list->items[index] = item;
    py_object_incref(item);
}

/* 元组操作 */
py_object* py_tuple_get_item(py_tuple_object* tuple, size_t index) {
    if (index >= tuple->length) {
        return NULL;
    }
    return tuple->items[index];
}

/* 对象操作函数 */
py_object* py_object_getattr(py_object* obj, const char* name) {
    switch (obj->type) {
        case PY_TYPE_MODULE: {
            py_module_object* module = (py_module_object*)obj;
            return py_dict_get_item(module->dict, py_string_new(name));
        }
        case PY_TYPE_TYPE: {
            py_type_object* type = (py_type_object*)obj;
            return py_dict_get_item(type->dict, py_string_new(name));
        }
        case PY_TYPE_DICT: {
            py_dict_object* dict = (py_dict_object*)obj;
            return py_dict_get_item(dict, py_string_new(name));
        }
        case PY_TYPE_LIST: {
            py_list_object* list = (py_list_object*)obj;
            if (strcmp(name, "append") == 0) {
                return py_native_function_new(py_list_append_method, "append");
            } else if (strcmp(name, "pop") == 0) {
                return py_native_function_new(py_list_pop_method, "pop");
            } else if (strcmp(name, "count") == 0) {
                return py_native_function_new(py_list_count_method, "count");
            }
            break;
        }
        case PY_TYPE_STRING: {
            py_string_object* str = (py_string_object*)obj;
            if (strcmp(name, "lower") == 0) {
                return py_native_function_new(py_string_lower_method, "lower");
            } else if (strcmp(name, "upper") == 0) {
                return py_native_function_new(py_string_upper_method, "upper");
            } else if (strcmp(name, "split") == 0) {
                return py_native_function_new(py_string_split_method, "split");
            }
            break;
        }
        default:
            break;
    }
    return NULL;
}

void py_object_setattr(py_object* obj, const char* name, py_object* value) {
    switch (obj->type) {
        case PY_TYPE_MODULE: {
            py_module_object* module = (py_module_object*)obj;
            py_dict_set_item(module->dict, py_string_new(name), value);
            break;
        }
        case PY_TYPE_TYPE: {
            py_type_object* type = (py_type_object*)obj;
            py_dict_set_item(type->dict, py_string_new(name), value);
            break;
        }
        case PY_TYPE_DICT: {
            py_dict_object* dict = (py_dict_object*)obj;
            py_dict_set_item(dict, py_string_new(name), value);
            break;
        }
        default:
            break;
    }
}

void py_object_delattr(py_object* obj, const char* name) {
    switch (obj->type) {
        case PY_TYPE_MODULE: {  // 修复：MODule -> MODULE
            py_module_object* module = (py_module_object*)obj;
            py_dict_del_item(module->dict, py_string_new(name));
            break;
        }
        case PY_TYPE_TYPE: {
            py_type_object* type = (py_type_object*)obj;
            py_dict_del_item(type->dict, py_string_new(name));
            break;
        }
        case PY_TYPE_DICT: {
            py_dict_object* dict = (py_dict_object*)obj;
            py_dict_del_item(dict, py_string_new(name));
            break;
        }
        default:
            break;
    }
}

py_object* py_object_call(py_object* func, py_object* args) {
    if (func->type == PY_TYPE_NATIVE_FUNCTION) {
        py_native_function_object* native_func = (py_native_function_object*)func;
        return native_func->function(NULL, args);
    }
    return NULL;
}

py_object* py_object_str(py_object* obj) {
    switch (obj->type) {
        case PY_TYPE_NONE:
            return py_string_new("None");
        case PY_TYPE_INT: {
            char buffer[32];
            snprintf(buffer, sizeof(buffer), "%lld", (long long)((py_int_object*)obj)->value);
            return py_string_new(buffer);
        }
        case PY_TYPE_FLOAT: {
            char buffer[64];
            snprintf(buffer, sizeof(buffer), "%g", ((py_float_object*)obj)->value);
            return py_string_new(buffer);
        }
        case PY_TYPE_BOOL:
            return py_string_new(((py_bool_object*)obj)->value ? "True" : "False");
        case PY_TYPE_STRING:
            return obj;
        case PY_TYPE_BYTES: {
            py_bytes_object* bytes = (py_bytes_object*)obj;
            return py_string_new((const char*)bytes->value);
        }
        case PY_TYPE_LIST: {
            py_list_object* list = (py_list_object*)obj;
            char* buffer = (char*)py_malloc(1024);
            buffer[0] = '[';
            size_t pos = 1;
            
            for (size_t i = 0; i < list->length; i++) {
                py_object* item_str = py_object_str(list->items[i]);
                const char* str_val = ((py_string_object*)item_str)->value;
                size_t len = strlen(str_val);
                
                if (pos + len + 2 > 1024) {
                    buffer = (char*)py_realloc(buffer, pos + len + 1024);
                }
                
                strcpy(buffer + pos, str_val);
                pos += len;
                
                if (i < list->length - 1) {
                    buffer[pos++] = ',';
                    buffer[pos++] = ' ';
                }
                
                py_object_decref(item_str);
            }
            
            buffer[pos++] = ']';
            buffer[pos] = '\0';
            
            py_object* result = py_string_new(buffer);
            py_free(buffer);
            return result;
        }
        case PY_TYPE_DICT: {
            py_dict_object* dict = (py_dict_object*)obj;
            char* buffer = (char*)py_malloc(1024);
            buffer[0] = '{';
            size_t pos = 1;
            bool first = true;
            
            for (size_t i = 0; i < dict->capacity; i++) {
                dict_entry* entry = dict->buckets[i];
                while (entry) {
                    if (!first) {
                        buffer[pos++] = ',';
                        buffer[pos++] = ' ';
                    }
                    
                    py_object* key_str = py_object_str(entry->key);
                    py_object* value_str = py_object_str(entry->value);
                    
                    const char* key_val = ((py_string_object*)key_str)->value;
                    const char* value_val = ((py_string_object*)value_str)->value;
                    
                    size_t key_len = strlen(key_val);
                    size_t value_len = strlen(value_val);
                    
                    if (pos + key_len + value_len + 3 > 1024) {
                        buffer = (char*)py_realloc(buffer, pos + key_len + value_len + 1024);
                    }
                    
                    strcpy(buffer + pos, key_val);
                    pos += key_len;
                    
                    buffer[pos++] = ':';
                    buffer[pos++] = ' ';
                    
                    strcpy(buffer + pos, value_val);
                    pos += value_len;
                    
                    py_object_decref(key_str);
                    py_object_decref(value_str);
                    
                    entry = entry->next;
                    first = false;
                }
            }
            
            buffer[pos++] = '}';
            buffer[pos] = '\0';
            
            py_object* result = py_string_new(buffer);
            py_free(buffer);
            return result;
        }
        default: {
            char buffer[64];
            snprintf(buffer, sizeof(buffer), "<%s object at %p>", 
                    obj->type == PY_TYPE_LIST ? "list" :
                    obj->type == PY_TYPE_TUPLE ? "tuple" :
                    obj->type == PY_TYPE_DICT ? "dict" :
                    obj->type == PY_TYPE_FUNCTION ? "function" :
                    obj->type == PY_TYPE_MODULE ? "module" :
                    obj->type == PY_TYPE_TYPE ? "type" : "object",
                    obj);
            return py_string_new(buffer);
        }
    }
}

py_object* py_object_repr(py_object* obj) {
    return py_object_str(obj);
}

py_object* py_object_add(py_object* left, py_object* right) {
    if (left->type == PY_TYPE_INT && right->type == PY_TYPE_INT) {
        return py_int_new(((py_int_object*)left)->value + ((py_int_object*)right)->value);
    }
    if (left->type == PY_TYPE_FLOAT && right->type == PY_TYPE_FLOAT) {
        return py_float_new(((py_float_object*)left)->value + ((py_float_object*)right)->value);
    }
    if (left->type == PY_TYPE_STRING && right->type == PY_TYPE_STRING) {
        py_string_object* str_left = (py_string_object*)left;
        py_string_object* str_right = (py_string_object*)right;
        
        char* buffer = (char*)py_malloc(str_left->length + str_right->length + 1);
        memcpy(buffer, str_left->value, str_left->length);
        memcpy(buffer + str_left->length, str_right->value, str_right->length);
        buffer[str_left->length + str_right->length] = '\0';
        
        py_object* result = py_string_new(buffer);
        py_free(buffer);
        return result;
    }
    if (left->type == PY_TYPE_LIST && right->type == PY_TYPE_LIST) {
        py_list_object* list_left = (py_list_object*)left;
        py_list_object* list_right = (py_list_object*)right;
        
        py_list_object* result = (py_list_object*)py_list_new(list_left->length + list_right->length);
        
        for (size_t i = 0; i < list_left->length; i++) {
            py_list_append(result, list_left->items[i]);
        }
        
        for (size_t i = 0; i < list_right->length; i++) {
            py_list_append(result, list_right->items[i]);
        }
        
        return (py_object*)result;
    }
    return NULL;
}

py_object* py_object_sub(py_object* left, py_object* right) {
    if (left->type == PY_TYPE_INT && right->type == PY_TYPE_INT) {
        return py_int_new(((py_int_object*)left)->value - ((py_int_object*)right)->value);
    }
    if (left->type == PY_TYPE_FLOAT && right->type == PY_TYPE_FLOAT) {
        return py_float_new(((py_float_object*)left)->value - ((py_float_object*)right)->value);
    }
    return NULL;
}

py_object* py_object_mul(py_object* left, py_object* right) {
    if (left->type == PY_TYPE_INT && right->type == PY_TYPE_INT) {
        return py_int_new(((py_int_object*)left)->value * ((py_int_object*)right)->value);
    }
    if (left->type == PY_TYPE_FLOAT && right->type == PY_TYPE_FLOAT) {
        return py_float_new(((py_float_object*)left)->value * ((py_float_object*)right)->value);
    }
    if (left->type == PY_TYPE_STRING && right->type == PY_TYPE_INT) {
        py_int count = ((py_int_object*)right)->value;
        if (count <= 0) return py_string_new("");
        
        py_string_object* str = (py_string_object*)left;
        size_t total_length = str->length * count;
        char* buffer = (char*)py_malloc(total_length + 1);
        buffer[0] = '\0';
        
        for (py_int i = 0; i < count; i++) {
            strcat(buffer, str->value);
        }
        
        py_object* result = py_string_new(buffer);
        py_free(buffer);
        return result;
    }
    if (left->type == PY_TYPE_INT && right->type == PY_TYPE_STRING) {
        return py_object_mul(right, left);
    }
    if (left->type == PY_TYPE_LIST && right->type == PY_TYPE_INT) {
        py_int count = ((py_int_object*)right)->value;
        if (count <= 0) return py_list_new(0);
        
        py_list_object* list = (py_list_object*)left;
        py_list_object* result = (py_list_object*)py_list_new(list->length * count);
        
        for (py_int i = 0; i < count; i++) {
            for (size_t j = 0; j < list->length; j++) {
                py_list_append(result, list->items[j]);
            }
        }
        
        return (py_object*)result;
    }
    return NULL;
}

py_object* py_object_div(py_object* left, py_object* right) {
    if (left->type == PY_TYPE_INT && right->type == PY_TYPE_INT) {
        if (((py_int_object*)right)->value == 0) {
            return NULL; /* 除零错误 */
        }
        return py_float_new((double)((py_int_object*)left)->value / (double)((py_int_object*)right)->value);
    }
    if (left->type == PY_TYPE_FLOAT && right->type == PY_TYPE_FLOAT) {
        if (((py_float_object*)right)->value == 0.0) {
            return NULL; /* 除零错误 */
        }
        return py_float_new(((py_float_object*)left)->value / ((py_float_object*)right)->value);
    }
    if (left->type == PY_TYPE_INT && right->type == PY_TYPE_FLOAT) {
        if (((py_float_object*)right)->value == 0.0) {
            return NULL; /* 除零错误 */
        }
        return py_float_new((double)((py_int_object*)left)->value / ((py_float_object*)right)->value);
    }
    if (left->type == PY_TYPE_FLOAT && right->type == PY_TYPE_INT) {
        if (((py_int_object*)right)->value == 0) {
            return NULL; /* 除零错误 */
        }
        return py_float_new(((py_float_object*)left)->value / (double)((py_int_object*)right)->value);
    }
    return NULL;
}

py_object* py_object_compare(py_object* left, py_object* right, int op) {
    int result = 0;
    
    if (left->type == PY_TYPE_INT && right->type == PY_TYPE_INT) {
        py_int a = ((py_int_object*)left)->value;
        py_int b = ((py_int_object*)right)->value;
        switch (op) {
            case 0: result = a < b; break;  /* LT */
            case 1: result = a <= b; break; /* LE */
            case 2: result = a == b; break; /* EQ */
            case 3: result = a != b; break; /* NE */
            case 4: result = a > b; break;  /* GT */
            case 5: result = a >= b; break; /* GE */
        }
    } else if (left->type == PY_TYPE_FLOAT && right->type == PY_TYPE_FLOAT) {
        py_float a = ((py_float_object*)left)->value;
        py_float b = ((py_float_object*)right)->value;
        switch (op) {
            case 0: result = a < b; break;
            case 1: result = a <= b; break;
            case 2: result = a == b; break;
            case 3: result = a != b; break;
            case 4: result = a > b; break;
            case 5: result = a >= b; break;
        }
    } else if (left->type == PY_TYPE_STRING && right->type == PY_TYPE_STRING) {
        int cmp = strcmp(((py_string_object*)left)->value, ((py_string_object*)right)->value);
        switch (op) {
            case 0: result = cmp < 0; break;
            case 1: result = cmp <= 0; break;
            case 2: result = cmp == 0; break;
            case 3: result = cmp != 0; break;
            case 4: result = cmp > 0; break;
            case 5: result = cmp >= 0; break;
        }
    } else {
        return NULL;
    }
    
    return py_bool_new(result);
}

/* 类型方法实现 */
py_object* py_list_append_method(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 2) {
        return NULL;
    }
    
    py_object* list_obj = tuple->items[0];
    py_object* item = tuple->items[1];
    
    if (list_obj->type != PY_TYPE_LIST) {
        return NULL;
    }
    
    py_list_append((py_list_object*)list_obj, item);
    return py_none_new();
}

py_object* py_list_pop_method(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length < 1) {
        return NULL;
    }
    
    py_object* list_obj = tuple->items[0];
    if (list_obj->type != PY_TYPE_LIST) {
        return NULL;
    }
    
    py_list_object* list = (py_list_object*)list_obj;
    if (list->length == 0) {
        return NULL;
    }
    
    py_int index = -1;
    if (tuple->length > 1) {
        if (tuple->items[1]->type != PY_TYPE_INT) {
            return NULL;
        }
        index = ((py_int_object*)tuple->items[1])->value;
    }
    
    if (index < 0) {
        index = list->length + index;
    }
    
    if (index < 0 || index >= (py_int)list->length) {
        return NULL;
    }
    
    py_object* result = list->items[index];
    py_object_incref(result);
    
    /* 移动剩余元素 */
    for (size_t i = index; i < list->length - 1; i++) {
        list->items[i] = list->items[i + 1];
    }
    
    list->length--;
    return result;
}

py_object* py_list_count_method(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 2) {
        return NULL;
    }
    
    py_object* list_obj = tuple->items[0];
    py_object* item = tuple->items[1];
    
    if (list_obj->type != PY_TYPE_LIST) {
        return NULL;
    }
    
    py_list_object* list = (py_list_object*)list_obj;
    py_int count = 0;
    
    for (size_t i = 0; i < list->length; i++) {
        if (py_object_equal(list->items[i], item)) {
            count++;
        }
    }
    
    return py_int_new(count);
}

py_object* py_string_lower_method(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 1) {
        return NULL;
    }
    
    py_object* str_obj = tuple->items[0];
    if (str_obj->type != PY_TYPE_STRING) {
        return NULL;
    }
    
    py_string_object* str = (py_string_object*)str_obj;
    char* buffer = (char*)py_malloc(str->length + 1);
    
    for (size_t i = 0; i < str->length; i++) {
        buffer[i] = tolower(str->value[i]);
    }
    buffer[str->length] = '\0';
    
    py_object* result = py_string_new(buffer);
    py_free(buffer);
    return result;
}

py_object* py_string_upper_method(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 1) {
        return NULL;
    }
    
    py_object* str_obj = tuple->items[0];
    if (str_obj->type != PY_TYPE_STRING) {
        return NULL;
    }
    
    py_string_object* str = (py_string_object*)str_obj;
    char* buffer = (char*)py_malloc(str->length + 1);
    
    for (size_t i = 0; i < str->length; i++) {
        buffer[i] = toupper(str->value[i]);
    }
    buffer[str->length] = '\0';
    
    py_object* result = py_string_new(buffer);
    py_free(buffer);
    return result;
}

py_object* py_string_split_method(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length < 1) {
        return NULL;
    }
    
    py_object* str_obj = tuple->items[0];
    if (str_obj->type != PY_TYPE_STRING) {
        return NULL;
    }
    
    py_string_object* str = (py_string_object*)str_obj;
    const char* delimiter = " ";
    
    if (tuple->length > 1) {
        if (tuple->items[1]->type != PY_TYPE_STRING) {
            return NULL;
        }
        delimiter = ((py_string_object*)tuple->items[1])->value;
    }
    
    py_list_object* result = (py_list_object*)py_list_new(0);
    const char* start = str->value;
    const char* end = str->value;
    size_t delim_len = strlen(delimiter);
    
    while (*end) {
        if (strncmp(end, delimiter, delim_len) == 0) {
            if (start != end) {
                py_object* part = py_string_new_with_length(start, end - start);
                py_list_append(result, part);
                py_object_decref(part);
            }
            start = end + delim_len;
            end = start;
        } else {
            end++;
        }
    }
    
    if (start != end) {
        py_object* part = py_string_new_with_length(start, end - start);
        py_list_append(result, part);
        py_object_decref(part);
    }
    
    return (py_object*)result;
}

/* 内置函数 */
py_object* py_builtin_print(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    for (size_t i = 0; i < tuple->length; i++) {
        py_object* str_obj = py_object_str(tuple->items[i]);
        printf("%s", ((py_string_object*)str_obj)->value);
        py_object_decref(str_obj);
        
        if (i < tuple->length - 1) {
            printf(" ");
        }
    }
    printf("\n");
    return py_none_new();
}

py_object* py_builtin_len(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 1) {
        return NULL;
    }
    
    py_object* obj = tuple->items[0];
    switch (obj->type) {
        case PY_TYPE_STRING:
            return py_int_new(((py_string_object*)obj)->length);
        case PY_TYPE_LIST:
            return py_int_new(((py_list_object*)obj)->length);
        case PY_TYPE_TUPLE:
            return py_int_new(((py_tuple_object*)obj)->length);
        case PY_TYPE_DICT:
            return py_int_new(((py_dict_object*)obj)->count);
        default:
            return NULL;
    }
}

py_object* py_builtin_range(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    py_int start = 0, stop = 0, step = 1;
    
    if (tuple->length == 1) {
        stop = ((py_int_object*)tuple->items[0])->value;
    } else if (tuple->length == 2) {
        start = ((py_int_object*)tuple->items[0])->value;
        stop = ((py_int_object*)tuple->items[1])->value;
    } else if (tuple->length == 3) {
        start = ((py_int_object*)tuple->items[0])->value;
        stop = ((py_int_object*)tuple->items[1])->value;
        step = ((py_int_object*)tuple->items[2])->value;
    } else {
        return NULL;
    }
    
    if (step == 0) {
        return NULL;
    }
    
    py_list_object* list = (py_list_object*)py_list_new(0);
    if (step > 0) {
        for (py_int i = start; i < stop; i += step) {
            py_list_append(list, py_int_new(i));
        }
    } else {
        for (py_int i = start; i > stop; i += step) {
            py_list_append(list, py_int_new(i));
        }
    }
    
    return (py_object*)list;
}

py_object* py_builtin_input(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length > 0) {
        py_object* prompt = py_object_str(tuple->items[0]);
        printf("%s", ((py_string_object*)prompt)->value);
        py_object_decref(prompt);
    }
    
    char buffer[1024];
    if (fgets(buffer, sizeof(buffer), stdin)) {
        /* 移除换行符 */
        size_t len = strlen(buffer);
        if (len > 0 && buffer[len-1] == '\n') {
            buffer[len-1] = '\0';
        }
        return py_string_new(buffer);
    }
    
    return py_string_new("");
}

py_object* py_builtin_open(py_object* self, py_object* args) {
    /* 简化实现：只支持读取文本文件 */
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length < 1) {
        return NULL;
    }
    
    py_object* filename_obj = tuple->items[0];
    if (filename_obj->type != PY_TYPE_STRING) {
        return NULL;
    }
    
    const char* filename = ((py_string_object*)filename_obj)->value;
    FILE* file = fopen(filename, "r");
    if (!file) {
        return NULL;
    }
    
    fseek(file, 0, SEEK_END);
    long size = ftell(file);
    fseek(file, 0, SEEK_SET);
    
    char* buffer = (char*)py_malloc(size + 1);
    fread(buffer, 1, size, file);
    buffer[size] = '\0';
    fclose(file);
    
    py_object* result = py_string_new(buffer);
    py_free(buffer);
    return result;
}

py_object* py_builtin_type(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 1) {
        return NULL;
    }
    
    py_object* obj = tuple->items[0];
    switch (obj->type) {
        case PY_TYPE_NONE:
            return py_string_new("NoneType");
        case PY_TYPE_INT:
            return py_string_new("int");
        case PY_TYPE_FLOAT:
            return py_string_new("float");
        case PY_TYPE_BOOL:
            return py_string_new("bool");
        case PY_TYPE_STRING:
            return py_string_new("str");
        case PY_TYPE_BYTES:
            return py_string_new("bytes");
        case PY_TYPE_LIST:
            return py_string_new("list");
        case PY_TYPE_TUPLE: {  // 修复：Tuple -> TUPLE
            return py_string_new("tuple");
        }
        case PY_TYPE_DICT:
            return py_string_new("dict");
        case PY_TYPE_FUNCTION:
            return py_string_new("function");
        case PY_TYPE_NATIVE_FUNCTION:
            return py_string_new("builtin_function");
        case PY_TYPE_MODULE:
            return py_string_new("module");
        case PY_TYPE_TYPE:
            return py_string_new("type");
        case PY_TYPE_EXCEPTION:
            return py_string_new("exception");
        default:
            return py_string_new("unknown");
    }
}

py_object* py_builtin_isinstance(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 2) {
        return NULL;
    }
    
    py_object* obj = tuple->items[0];
    py_object* type_obj = tuple->items[1];
    
    if (type_obj->type != PY_TYPE_TYPE) {
        return NULL;
    }
    
    py_type_object* type = (py_type_object*)type_obj;
    return py_bool_new(obj->type == type->base_type);
}

py_object* py_builtin_issubclass(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 2) {
        return NULL;
    }
    
    py_object* cls1_obj = tuple->items[0];
    py_object* cls2_obj = tuple->items[1];
    
    if (cls1_obj->type != PY_TYPE_TYPE || cls2_obj->type != PY_TYPE_TYPE) {
        return NULL;
    }
    
    py_type_object* cls1 = (py_type_object*)cls1_obj;
    py_type_object* cls2 = (py_type_object*)cls2_obj;
    
    /* 简化实现：只检查直接继承关系 */
    return py_bool_new(cls1->base_type == cls2->base_type);
}

py_object* py_builtin_hasattr(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 2) {
        return NULL;
    }
    
    py_object* obj = tuple->items[0];
    py_object* name_obj = tuple->items[1];
    
    if (name_obj->type != PY_TYPE_STRING) {
        return NULL;
    }
    
    const char* name = ((py_string_object*)name_obj)->value;
    py_object* attr = py_object_getattr(obj, name);
    return py_bool_new(attr != NULL);
}

py_object* py_builtin_getattr(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length < 2 || tuple->length > 3) {
        return NULL;
    }
    
    py_object* obj = tuple->items[0];
    py_object* name_obj = tuple->items[1];
    
    if (name_obj->type != PY_TYPE_STRING) {
        return NULL;
    }
    
    const char* name = ((py_string_object*)name_obj)->value;
    py_object* attr = py_object_getattr(obj, name);
    
    if (attr) {
        return attr;
    }
    
    if (tuple->length == 3) {
        return tuple->items[2];
    }
    
    return NULL;
}

py_object* py_builtin_setattr(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 3) {
        return NULL;
    }
    
    py_object* obj = tuple->items[0];
    py_object* name_obj = tuple->items[1];
    py_object* value = tuple->items[2];
    
    if (name_obj->type != PY_TYPE_STRING) {
        return NULL;
    }
    
    const char* name = ((py_string_object*)name_obj)->value;
    py_object_setattr(obj, name, value);
    return py_none_new();
}

py_object* py_builtin_delattr(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 2) {
        return NULL;
    }
    
    py_object* obj = tuple->items[0];
    py_object* name_obj = tuple->items[1];
    
    if (name_obj->type != PY_TYPE_STRING) {
        return NULL;
    }
    
    const char* name = ((py_string_object*)name_obj)->value;
    py_object_delattr(obj, name);
    return py_none_new();
}

py_object* py_builtin_dir(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 1) {
        return NULL;
    }
    
    py_object* obj = tuple->items[0];
    py_list_object* list = (py_list_object*)py_list_new(0);
    
    switch (obj->type) {
        case PY_TYPE_MODULE: {
            py_module_object* module = (py_module_object*)obj;
            for (size_t i = 0; i < module->dict->capacity; i++) {
                dict_entry* entry = module->dict->buckets[i];
                while (entry) {
                    py_list_append(list, entry->key);
                    entry = entry->next;
                }
            }
            break;
        }
        case PY_TYPE_TYPE: {
            py_type_object* type = (py_type_object*)obj;
            for (size_t i = 0; i < type->dict->capacity; i++) {
                dict_entry* entry = type->dict->buckets[i];
                while (entry) {
                    py_list_append(list, entry->key);
                    entry = entry->next;
                }
            }
            break;
        }
        case PY_TYPE_DICT: {
            py_dict_object* dict = (py_dict_object*)obj;
            for (size_t i = 0; i < dict->capacity; i++) {
                dict_entry* entry = dict->buckets[i];
                while (entry) {
                    py_list_append(list, entry->key);
                    entry = entry->next;
                }
            }
            break;
        }
        default:
            break;
    }
    
    return (py_object*)list;
}

py_object* py_builtin_abs(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length != 1) {
        return NULL;
    }
    
    py_object* obj = tuple->items[0];
    if (obj->type == PY_TYPE_INT) {
        py_int value = ((py_int_object*)obj)->value;
        return py_int_new(value < 0 ? -value : value);
    } else if (obj->type == PY_TYPE_FLOAT) {
        py_float value = ((py_float_object*)obj)->value;
        return py_float_new(value < 0 ? -value : value);
    }
    
    return NULL;
}

py_object* py_builtin_max(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length == 0) {
        return NULL;
    }
    
    py_object* max_obj = tuple->items[0];
    for (size_t i = 1; i < tuple->length; i++) {
        py_object* cmp_result = py_object_compare(max_obj, tuple->items[i], 0); // LT
        if (cmp_result && ((py_bool_object*)cmp_result)->value) {
            max_obj = tuple->items[i];
        }
        if (cmp_result) py_object_decref(cmp_result);
    }
    
    py_object_incref(max_obj);
    return max_obj;
}

py_object* py_builtin_min(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length == 0) {
        return NULL;
    }
    
    py_object* min_obj = tuple->items[0];
    for (size_t i = 1; i < tuple->length; i++) {
        py_object* cmp_result = py_object_compare(min_obj, tuple->items[i], 4); // GT
        if (cmp_result && ((py_bool_object*)cmp_result)->value) {
            min_obj = tuple->items[i];
        }
        if (cmp_result) py_object_decref(cmp_result);
    }
    
    py_object_incref(min_obj);
    return min_obj;
}

py_object* py_builtin_sum(py_object* self, py_object* args) {
    py_tuple_object* tuple = (py_tuple_object*)args;
    if (tuple->length < 1) {
        return NULL;
    }
    
    py_object* iterable = tuple->items[0];
    if (iterable->type != PY_TYPE_LIST && iterable->type != PY_TYPE_TUPLE) {
        return NULL;
    }
    
    py_object* sum_obj = py_int_new(0);
    
    if (iterable->type == PY_TYPE_LIST) {
        py_list_object* list = (py_list_object*)iterable;
        for (size_t i = 0; i < list->length; i++) {
            py_object* new_sum = py_object_add(sum_obj, list->items[i]);
            if (!new_sum) {
                py_object_decref(sum_obj);
                return NULL;
            }
            py_object_decref(sum_obj);
            sum_obj = new_sum;
        }
    } else {
        py_tuple_object* tup = (py_tuple_object*)iterable;
        for (size_t i = 0; i < tup->length; i++) {
            py_object* new_sum = py_object_add(sum_obj, tup->items[i]);
            if (!new_sum) {
                py_object_decref(sum_obj);
                return NULL;
            }
            py_object_decref(sum_obj);
            sum_obj = new_sum;
        }
    }
    
    return sum_obj;
}

/* 导入支持函数 */
static char* find_module_path(const char* name) {
    /* 在当前目录查找 */
    char* path = (char*)py_malloc(strlen(name) + 10);
    sprintf(path, "%s.py", name);
    
    FILE* file = fopen(path, "r");
    if (file) {
        fclose(file);
        return path;
    }
    py_free(path);
    
    /* 在PYTHONPATH环境变量指定的路径中查找 */
    char* pythonpath = getenv("PYTHONPATH");
    if (!pythonpath) {
        return NULL;
    }
    
    char* path_copy = strdup(pythonpath);
    char* dir = strtok(path_copy, ":");
    while (dir) {
        path = (char*)py_malloc(strlen(dir) + strlen(name) + 10);
        sprintf(path, "%s/%s.py", dir, name);
        
        file = fopen(path, "r");
        if (file) {
            fclose(file);
            free(path_copy);
            return path;
        }
        py_free(path);
        
        dir = strtok(NULL, ":");
    }
    
    free(path_copy);
    return NULL;
}

py_object* py_import_module(py_vm* vm, const char* name) {
    /* 检查模块是否已加载 */
    py_object* key = py_string_new(name);
    py_object* module = py_dict_get_item((py_dict_object*)vm->modules, key);
    py_object_decref(key);
    
    if (module) {
        return module;
    }
    
    /* 查找模块文件 */
    char* path = find_module_path(name);
    if (!path) {
        return NULL;
    }
    
    /* 读取模块源代码 */
    FILE* file = fopen(path, "r");
    if (!file) {
        py_free(path);
        return NULL;
    }
    
    fseek(file, 0, SEEK_END);
    long size = ftell(file);
    fseek(file, 0, SEEK_SET);
    
    char* source = (char*)py_malloc(size + 1);
    fread(source, 1, size, file);
    source[size] = '\0';
    fclose(file);
    py_free(path);
    
    /* 编译并执行模块 */
    py_code_object* code = py_compile(source, name, 0);
    py_free(source);
    
    if (!code) {
        return NULL;
    }
    
    /* 创建模块对象 */
    module = py_module_new(name);
    py_vm_register_module(vm, name, module);
    
    /* 执行模块代码 */
    py_vm* prev_vm = current_vm;
    current_vm = vm;
    
    py_frame* frame = (py_frame*)py_malloc(sizeof(py_frame));
    frame->stack_size = code->stack_size;
    frame->stack = (py_object**)py_malloc(sizeof(py_object*) * frame->stack_size);
    frame->stack_pointer = 0;
    frame->locals = (py_object**)py_malloc(sizeof(py_object*) * code->local_count);
    memset(frame->locals, 0, sizeof(py_object*) * code->local_count);
    frame->globals = (py_object*)((py_module_object*)module)->dict;
    frame->builtins = (py_object*)vm->builtins;
    frame->exception = NULL;
    frame->traceback = NULL;
    frame->last_instruction = 0;
    frame->code = code;
    py_object_incref((py_object*)code);
    frame->previous = (struct py_frame*)vm->current_frame;
    
    vm->current_frame = frame;
    
    /* 执行字节码 */
    jmp_buf exit_jmp;
    py_object* result = NULL;
    
    if (setjmp(exit_jmp) == 0) {
        unsigned char* ip = code->code;
        while (ip < code->code + code->code_length) {
            opcode op = (opcode)*ip++;
            
            switch (op) {
                case OP_LOAD_CONST: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    py_object* constant = ((py_tuple_object*)code->consts)->items[index];
                    frame->stack[frame->stack_pointer++] = constant;
                    py_object_incref(constant);
                    break;
                }
                case OP_LOAD_NAME: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    py_object* name = ((py_tuple_object*)code->names)->items[index];
                    const char* name_str = ((py_string_object*)name)->value;
                    
                    /* 先在局部变量中查找 */
                    py_object* value = NULL;
                    for (int i = 0; i < code->local_count; i++) {
                        if (frame->locals[i] && 
                            frame->locals[i]->type == PY_TYPE_STRING &&
                            strcmp(((py_string_object*)frame->locals[i])->value, name_str) == 0) {
                            value = frame->locals[i + 1]; /* 值在名称后面 */
                            break;
                        }
                    }
                    
                    /* 然后在全局变量中查找 */
                    if (!value) {
                        value = py_dict_get_item((py_dict_object*)frame->globals, name);
                    }
                    
                    /* 最后在内置函数中查找 */
                    if (!value) {
                        value = py_dict_get_item((py_dict_object*)frame->builtins, name);
                    }
                    
                    if (value) {
                        frame->stack[frame->stack_pointer++] = value;
                        py_object_incref(value);
                    } else {
                        /* 名称未找到错误 */
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_STORE_NAME: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    py_object* name = ((py_tuple_object*)code->names)->items[index];
                    py_object* value = frame->stack[--frame->stack_pointer];
                    
                    /* 存储在局部变量中 */
                    for (int i = 0; i < code->local_count; i++) {
                        if (frame->locals[i] && 
                            frame->locals[i]->type == PY_TYPE_STRING &&
                            py_object_equal(frame->locals[i], name)) {
                            py_object_decref(frame->locals[i + 1]);
                            frame->locals[i + 1] = value;
                            py_object_incref(value);
                            break;
                        }
                    }
                    
                    /* 如果没有找到局部变量，存储在全局变量中 */
                    py_dict_set_item((py_dict_object*)frame->globals, name, value);
                    break;
                }
                case OP_LOAD_GLOBAL: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    py_object* name = ((py_tuple_object*)code->names)->items[index];
                    py_object* value = py_dict_get_item((py_dict_object*)frame->builtins, name);
                    
                    if (value) {
                        frame->stack[frame->stack_pointer++] = value;
                        py_object_incref(value);
                    } else {
                        /* 全局名称未找到错误 */
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_CALL_FUNCTION: {
                    uint16_t arg_count = *(uint16_t*)ip;
                    ip += 2;
                    
                    if (frame->stack_pointer < arg_count + 1) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    py_object* func = frame->stack[frame->stack_pointer - arg_count - 1];
                    
                    if (func->type == PY_TYPE_NATIVE_FUNCTION) {
                        /* 调用原生函数 */
                        py_native_function_object* native_func = (py_native_function_object*)func;
                        
                        /* 准备参数元组 */
                        py_tuple_object* args = (py_tuple_object*)py_tuple_new(arg_count);
                        for (uint16_t i = 0; i < arg_count; i++) {
                            args->items[i] = frame->stack[frame->stack_pointer - arg_count + i];
                            py_object_incref(args->items[i]);
                        }
                        
                        /* 调用函数 */
                        result = native_func->function(NULL, (py_object*)args);
                        py_object_decref((py_object*)args);
                        
                        /* 清理栈 */
                        frame->stack_pointer -= arg_count + 1;
                        frame->stack[frame->stack_pointer++] = result;
                        py_object_incref(result);
                    } else {
                        /* 不支持其他类型的函数调用 */
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_RETURN_VALUE: {
                    result = frame->stack[--frame->stack_pointer];
                    py_object_incref(result);
                    break;
                }
                case OP_BINARY_ADD: {  // 修复：OP_BINARY_Add -> OP_BINARY_ADD
                    if (frame->stack_pointer < 2) {
                        longjmp(exit_jmp, 1);
                    }
                    py_object* right = frame->stack[--frame->stack_pointer];
                    py_object* left = frame->stack[--frame->stack_pointer];
                    py_object* sum = py_object_add(left, right);
                    if (sum) {
                        frame->stack[frame->stack_pointer++] = sum;
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_BINARY_SUBTRACT: {
                    if (frame->stack_pointer < 2) {
                        longjmp(exit_jmp, 1);
                    }
                    py_object* right = frame->stack[--frame->stack_pointer];
                    py_object* left = frame->stack[--frame->stack_pointer];
                    py_object* diff = py_object_sub(left, right);
                    if (diff) {
                        frame->stack[frame->stack_pointer++] = diff;
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_BINARY_MULTIPLY: {
                    if (frame->stack_pointer < 2) {
                        longjmp(exit_jmp, 1);
                    }
                    py_object* right = frame->stack[--frame->stack_pointer];
                    py_object* left = frame->stack[--frame->stack_pointer];
                    py_object* product = py_object_mul(left, right);
                    if (product) {
                        frame->stack[frame->stack_pointer++] = product;
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_BINARY_DIVIDE: {
                    if (frame->stack_pointer < 2) {
                        longjmp(exit_jmp, 1);
                    }
                    py_object* right = frame->stack[--frame->stack_pointer];
                    py_object* left = frame->stack[--frame->stack_pointer];
                    py_object* quotient = py_object_div(left, right);
                    if (quotient) {
                        frame->stack[frame->stack_pointer++] = quotient;
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_COMPARE_OP: {
                    if (frame->stack_pointer < 2) {
                        longjmp(exit_jmp, 1);
                    }
                    uint8_t compare_op = *ip++;
                    py_object* right = frame->stack[--frame->stack_pointer];
                    py_object* left = frame->stack[--frame->stack_pointer];
                    py_object* result = py_object_compare(left, right, compare_op);
                    if (result) {
                        frame->stack[frame->stack_pointer++] = result;
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_POP_TOP: {
                    if (frame->stack_pointer < 1) {
                        longjmp(exit_jmp, 1);
                    }
                    py_object_decref(frame->stack[--frame->stack_pointer]);
                    break;
                }
                case OP_DUP_TOP: {
                    if (frame->stack_pointer < 1) {
                        longjmp(exit_jmp, 1);
                    }
                    py_object* top = frame->stack[frame->stack_pointer - 1];
                    frame->stack[frame->stack_pointer++] = top;
                    py_object_incref(top);
                    break;
                }
                case OP_JUMP_IF_FALSE: {
                    uint16_t target = *(uint16_t*)ip;
                    ip += 2;
                    
                    if (frame->stack_pointer < 1) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    py_object* condition = frame->stack[--frame->stack_pointer];
                    bool is_false = false;
                    
                    if (condition->type == PY_TYPE_BOOL) {
                        is_false = !((py_bool_object*)condition)->value;
                    } else if (condition->type == PY_TYPE_NONE) {
                        is_false = true;
                    } else if (condition->type == PY_TYPE_INT) {
                        is_false = ((py_int_object*)condition)->value == 0;
                    }
                    
                    py_object_decref(condition);
                    
                    if (is_false) {
                        ip = code->code + target;
                    }
                    break;
                }
                case OP_JUMP_FORWARD: {
                    uint16_t offset = *(uint16_t*)ip;
                    ip += 2;
                    ip += offset;
                    break;
                }
                case OP_JUMP_ABSOLUTE: {
                    uint16_t target = *(uint16_t*)ip;
                    ip += 2;
                    ip = code->code + target;
                    break;
                }
                case OP_POP_JUMP_IF_TRUE: {
                    uint16_t target = *(uint16_t*)ip;
                    ip += 2;
                    
                    if (frame->stack_pointer < 1) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    py_object* condition = frame->stack[--frame->stack_pointer];
                    bool is_true = false;
                    
                    if (condition->type == PY_TYPE_BOOL) {
                        is_true = ((py_bool_object*)condition)->value;
                    } else if (condition->type == PY_TYPE_INT) {
                        is_true = ((py_int_object*)condition)->value != 0;
                    } else if (condition->type != PY_TYPE_NONE) {
                        is_true = true;
                    }
                    
                    py_object_decref(condition);
                    
                    if (is_true) {
                        ip = code->code + target;
                    }
                    break;
                }
                case OP_LOAD_FAST: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    
                    if (index >= (uint16_t)code->local_count) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    py_object* value = frame->locals[index];
                    if (value) {
                        frame->stack[frame->stack_pointer++] = value;
                        py_object_incref(value);
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_STORE_FAST: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    
                    if (index >= (uint16_t)code->local_count) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    py_object* value = frame->stack[--frame->stack_pointer];
                    py_object_decref(frame->locals[index]);
                    frame->locals[index] = value;
                    py_object_incref(value);
                    break;
                }
                case OP_LOAD_ATTR: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    
                    if (frame->stack_pointer < 1) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    py_object* obj = frame->stack[--frame->stack_pointer];
                    py_object* name = ((py_tuple_object*)code->names)->items[index];
                    
                    if (name->type != PY_TYPE_STRING) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    const char* attr_name = ((py_string_object*)name)->value;
                    py_object* attr = py_object_getattr(obj, attr_name);
                    
                    if (attr) {
                        frame->stack[frame->stack_pointer++] = attr;
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                default:
                    fprintf(stderr, "Unknown opcode: %d\n", op);
                    longjmp(exit_jmp, 1);
            }
        }
    }
    
    /* 清理栈帧 */
    vm->current_frame = (py_frame*)frame->previous;
    
    for (int i = 0; i < frame->stack_pointer; i++) {
        py_object_decref(frame->stack[i]);
    }
    py_free(frame->stack);
    
    for (int i = 0; i < code->local_count; i++) {
        py_object_decref(frame->locals[i]);
    }
    py_free(frame->locals);
    
    py_object_decref((py_object*)frame->code);
    py_free(frame);
    
    current_vm = prev_vm;
    py_object_decref((py_object*)code);
    
    return module;
}

/* 虚拟机实现 */
py_vm* py_vm_new(void) {
    py_vm* vm = (py_vm*)py_malloc(sizeof(py_vm));
    vm->modules = (py_object*)py_dict_new(0);
    vm->builtins = (py_object*)py_dict_new(0);
    vm->current_frame = NULL;
    vm->gc_enabled = true;
    vm->gc_head = NULL;
    vm->gc_threshold = 1000;
    vm->gc_count = 0;
    
    /* 注册内置函数 */
    py_vm_register_builtin(vm, "print", py_builtin_print);
    py_vm_register_builtin(vm, "len", py_builtin_len);
    py_vm_register_builtin(vm, "range", py_builtin_range);
    py_vm_register_builtin(vm, "input", py_builtin_input);
    py_vm_register_builtin(vm, "open", py_builtin_open);
    py_vm_register_builtin(vm, "type", py_builtin_type);
    py_vm_register_builtin(vm, "isinstance", py_builtin_isinstance);
    py_vm_register_builtin(vm, "issubclass", py_builtin_issubclass);
    py_vm_register_builtin(vm, "hasattr", py_builtin_hasattr);
    py_vm_register_builtin(vm, "getattr", py_builtin_getattr);
    py_vm_register_builtin(vm, "setattr", py_builtin_setattr);
    py_vm_register_builtin(vm, "delattr", py_builtin_delattr);
    py_vm_register_builtin(vm, "dir", py_builtin_dir);
    py_vm_register_builtin(vm, "abs", py_builtin_abs);
    py_vm_register_builtin(vm, "max", py_builtin_max);
    py_vm_register_builtin(vm, "min", py_builtin_min);
    py_vm_register_builtin(vm, "sum", py_builtin_sum);
    
    return vm;
}

void py_vm_free(py_vm* vm) {
    /* 释放所有对象 */
    py_gc_collect(vm);
    
    /* 确保所有对象都被释放 */
    while (vm->gc_head) {
        py_gc_collect(vm);
    }
    
    py_object_decref(vm->modules);
    py_object_decref(vm->builtins);
    py_free(vm);
}

/* 字节码执行 */
py_object* py_vm_run(py_vm* vm, py_code_object* code) {
    /* 设置当前虚拟机 */
    py_vm* prev_vm = current_vm;
    current_vm = vm;
    
    /* 创建新的栈帧 */
    py_frame* frame = (py_frame*)py_malloc(sizeof(py_frame));
    frame->stack_size = code->stack_size;
    frame->stack = (py_object**)py_malloc(sizeof(py_object*) * frame->stack_size);
    frame->stack_pointer = 0;
    frame->locals = (py_object**)py_malloc(sizeof(py_object*) * code->local_count);
    memset(frame->locals, 0, sizeof(py_object*) * code->local_count);
    
    /* 创建全局字典 */
    py_object* globals_dict = (py_object*)py_dict_new(0);
    frame->globals = (py_object*)globals_dict;
    
    py_object* builtins_dict = vm->builtins;
    frame->builtins = builtins_dict;
    
    frame->exception = NULL;
    frame->traceback = NULL;
    frame->last_instruction = 0;
    frame->code = code;
    py_object_incref((py_object*)code);
    frame->previous = (struct py_frame*)vm->current_frame;
    
    vm->current_frame = frame;
    
    /* 执行字节码 */
    jmp_buf exit_jmp;
    py_object* result = NULL;
    
    if (setjmp(exit_jmp) == 0) {
        /* 正常执行路径 */
        unsigned char* ip = code->code;
        while (ip < code->code + code->code_length) {
            opcode op = (opcode)*ip++;
            
            switch (op) {
                case OP_LOAD_CONST: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    py_object* constant = ((py_tuple_object*)code->consts)->items[index];
                    frame->stack[frame->stack_pointer++] = constant;
                    py_object_incref(constant);
                    break;
                }
                case OP_LOAD_NAME: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    py_object* name = ((py_tuple_object*)code->names)->items[index];
                    const char* name_str = ((py_string_object*)name)->value;
                    
                    /* 先在局部变量中查找 */
                    py_object* value = NULL;
                    for (int i = 0; i < code->local_count; i++) {
                        if (frame->locals[i] && 
                            frame->locals[i]->type == PY_TYPE_STRING &&
                            strcmp(((py_string_object*)frame->locals[i])->value, name_str) == 0) {
                            value = frame->locals[i + 1]; /* 值在名称后面 */
                            break;
                        }
                    }
                    
                    /* 然后在全局变量中查找 */
                    if (!value) {
                        value = py_dict_get_item((py_dict_object*)frame->globals, name);
                    }
                    
                    /* 最后在内置函数中查找 */
                    if (!value) {
                        value = py_dict_get_item((py_dict_object*)frame->builtins, name);
                    }
                    
                    if (value) {
                        frame->stack[frame->stack_pointer++] = value;
                        py_object_incref(value);
                    } else {
                        /* 名称未找到错误 */
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_STORE_NAME: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    py_object* name = ((py_tuple_object*)code->names)->items[index];
                    py_object* value = frame->stack[--frame->stack_pointer];
                    
                    /* 存储在局部变量中 */
                    for (int i = 0; i < code->local_count; i++) {
                        if (frame->locals[i] && 
                            frame->locals[i]->type == PY_TYPE_STRING &&
                            py_object_equal(frame->locals[i], name)) {
                            py_object_decref(frame->locals[i + 1]);
                            frame->locals[i + 1] = value;
                            py_object_incref(value);
                            break;
                        }
                    }
                    
                    /* 如果没有找到局部变量，存储在全局变量中 */
                    py_dict_set_item((py_dict_object*)frame->globals, name, value);
                    break;
                }
                case OP_LOAD_GLOBAL: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    py_object* name = ((py_tuple_object*)code->names)->items[index];
                    py_object* value = py_dict_get_item((py_dict_object*)frame->builtins, name);
                    
                    if (value) {
                        frame->stack[frame->stack_pointer++] = value;
                        py_object_incref(value);
                    } else {
                        /* 全局名称未找到错误 */
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_CALL_FUNCTION: {
                    uint16_t arg_count = *(uint16_t*)ip;
                    ip += 2;
                    
                    if (frame->stack_pointer < arg_count + 1) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    py_object* func = frame->stack[frame->stack_pointer - arg_count - 1];
                    
                    if (func->type == PY_TYPE_NATIVE_FUNCTION) {
                        /* 调用原生函数 */
                        py_native_function_object* native_func = (py_native_function_object*)func;
                        
                        /* 准备参数元组 */
                        py_tuple_object* args = (py_tuple_object*)py_tuple_new(arg_count);
                        for (uint16_t i = 0; i < arg_count; i++) {
                            args->items[i] = frame->stack[frame->stack_pointer - arg_count + i];
                            py_object_incref(args->items[i]);
                        }
                        
                        /* 调用函数 */
                        result = native_func->function(NULL, (py_object*)args);
                        py_object_decref((py_object*)args);
                        
                        /* 清理栈 */
                        frame->stack_pointer -= arg_count + 1;
                        frame->stack[frame->stack_pointer++] = result;
                        py_object_incref(result);
                    } else {
                        /* 不支持其他类型的函数调用 */
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_RETURN_VALUE: {
                    result = frame->stack[--frame->stack_pointer];
                    py_object_incref(result);
                    break;
                }
                case OP_BINARY_ADD: {  // 修复：OP_BINARY_Add -> OP_BINARY_ADD
                    if (frame->stack_pointer < 2) {
                        longjmp(exit_jmp, 1);
                    }
                    py_object* right = frame->stack[--frame->stack_pointer];
                    py_object* left = frame->stack[--frame->stack_pointer];
                    py_object* sum = py_object_add(left, right);
                    if (sum) {
                        frame->stack[frame->stack_pointer++] = sum;
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_BINARY_SUBTRACT: {
                    if (frame->stack_pointer < 2) {
                        longjmp(exit_jmp, 1);
                    }
                    py_object* right = frame->stack[--frame->stack_pointer];
                    py_object* left = frame->stack[--frame->stack_pointer];
                    py_object* diff = py_object_sub(left, right);
                    if (diff) {
                        frame->stack[frame->stack_pointer++] = diff;
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_BINARY_MULTIPLY: {
                    if (frame->stack_pointer < 2) {
                        longjmp(exit_jmp, 1);
                    }
                    py_object* right = frame->stack[--frame->stack_pointer];
                    py_object* left = frame->stack[--frame->stack_pointer];
                    py_object* product = py_object_mul(left, right);
                    if (product) {
                        frame->stack[frame->stack_pointer++] = product;
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_BINARY_DIVIDE: {
                    if (frame->stack_pointer < 2) {
                        longjmp(exit_jmp, 1);
                    }
                    py_object* right = frame->stack[--frame->stack_pointer];
                    py_object* left = frame->stack[--frame->stack_pointer];
                    py_object* quotient = py_object_div(left, right);
                    if (quotient) {
                        frame->stack[frame->stack_pointer++] = quotient;
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_COMPARE_OP: {
                    if (frame->stack_pointer < 2) {
                        longjmp(exit_jmp, 1);
                    }
                    uint8_t compare_op = *ip++;
                    py_object* right = frame->stack[--frame->stack_pointer];
                    py_object* left = frame->stack[--frame->stack_pointer];
                    py_object* result = py_object_compare(left, right, compare_op);
                    if (result) {
                        frame->stack[frame->stack_pointer++] = result;
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_POP_TOP: {
                    if (frame->stack_pointer < 1) {
                        longjmp(exit_jmp, 1);
                    }
                    py_object_decref(frame->stack[--frame->stack_pointer]);
                    break;
                }
                case OP_DUP_TOP: {
                    if (frame->stack_pointer < 1) {
                        longjmp(exit_jmp, 1);
                    }
                    py_object* top = frame->stack[frame->stack_pointer - 1];
                    frame->stack[frame->stack_pointer++] = top;
                    py_object_incref(top);
                    break;
                }
                case OP_JUMP_IF_FALSE: {
                    uint16_t target = *(uint16_t*)ip;
                    ip += 2;
                    
                    if (frame->stack_pointer < 1) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    py_object* condition = frame->stack[--frame->stack_pointer];
                    bool is_false = false;
                    
                    if (condition->type == PY_TYPE_BOOL) {
                        is_false = !((py_bool_object*)condition)->value;
                    } else if (condition->type == PY_TYPE_NONE) {
                        is_false = true;
                    } else if (condition->type == PY_TYPE_INT) {
                        is_false = ((py_int_object*)condition)->value == 0;
                    }
                    
                    py_object_decref(condition);
                    
                    if (is_false) {
                        ip = code->code + target;
                    }
                    break;
                }
                case OP_JUMP_FORWARD: {
                    uint16_t offset = *(uint16_t*)ip;
                    ip += 2;
                    ip += offset;
                    break;
                }
                case OP_JUMP_ABSOLUTE: {
                    uint16_t target = *(uint16_t*)ip;
                    ip += 2;
                    ip = code->code + target;
                    break;
                }
                case OP_POP_JUMP_IF_TRUE: {
                    uint16_t target = *(uint16_t*)ip;
                    ip += 2;
                    
                    if (frame->stack_pointer < 1) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    py_object* condition = frame->stack[--frame->stack_pointer];
                    bool is_true = false;
                    
                    if (condition->type == PY_TYPE_BOOL) {
                        is_true = ((py_bool_object*)condition)->value;
                    } else if (condition->type == PY_TYPE_INT) {
                        is_true = ((py_int_object*)condition)->value != 0;
                    } else if (condition->type != PY_TYPE_NONE) {
                        is_true = true;
                    }
                    
                    py_object_decref(condition);
                    
                    if (is_true) {
                        ip = code->code + target;
                    }
                    break;
                }
                case OP_LOAD_FAST: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    
                    if (index >= (uint16_t)code->local_count) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    py_object* value = frame->locals[index];
                    if (value) {
                        frame->stack[frame->stack_pointer++] = value;
                        py_object_incref(value);
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                case OP_STORE_FAST: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    
                    if (index >= (uint16_t)code->local_count) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    py_object* value = frame->stack[--frame->stack_pointer];
                    py_object_decref(frame->locals[index]);
                    frame->locals[index] = value;
                    py_object_incref(value);
                    break;
                }
                case OP_LOAD_ATTR: {
                    uint16_t index = *(uint16_t*)ip;
                    ip += 2;
                    
                    if (frame->stack_pointer < 1) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    py_object* obj = frame->stack[--frame->stack_pointer];
                    py_object* name = ((py_tuple_object*)code->names)->items[index];
                    
                    if (name->type != PY_TYPE_STRING) {
                        longjmp(exit_jmp, 1);
                    }
                    
                    const char* attr_name = ((py_string_object*)name)->value;
                    py_object* attr = py_object_getattr(obj, attr_name);
                    
                    if (attr) {
                        frame->stack[frame->stack_pointer++] = attr;
                    } else {
                        longjmp(exit_jmp, 1);
                    }
                    break;
                }
                default:
                    fprintf(stderr, "Unknown opcode: %d\n", op);
                    longjmp(exit_jmp, 1);
            }
        }
    } else {
        /* 异常处理路径 */
        result = NULL;
    }
    
    /* 清理栈帧 */
    vm->current_frame = (py_frame*)frame->previous;
    
    for (int i = 0; i < frame->stack_pointer; i++) {
        py_object_decref(frame->stack[i]);
    }
    py_free(frame->stack);
    
    for (int i = 0; i < code->local_count; i++) {
        py_object_decref(frame->locals[i]);
    }
    py_free(frame->locals);
    
    py_object_decref(frame->globals);
    py_object_decref(frame->exception);
    py_object_decref(frame->traceback);
    py_object_decref((py_object*)frame->code);
    
    py_free(frame);
    
    /* 恢复之前的虚拟机 */
    current_vm = prev_vm;
    
    /* 返回结果 */
    return result ? result : py_none_new();
}

void py_vm_register_module(py_vm* vm, const char* name, py_object* module) {
    py_object* key = py_string_new(name);
    py_object* value = module;
    py_object_incref(value);
    
    py_dict_set_item((py_dict_object*)vm->modules, key, value);
    py_object_decref(key);
}

void py_vm_register_builtin(py_vm* vm, const char* name, py_native_function func) {
    py_object* key = py_string_new(name);
    py_object* value = py_native_function_new(func, name);
    
    py_dict_set_item((py_dict_object*)vm->builtins, key, value);
    py_object_decref(key);
}

/* 编译器实现（简化版） */
py_code_object* py_compile(const char* source, const char* filename, int mode) {
    /* 简化实现：只支持非常有限的语法 */
    py_code_object* code = (py_code_object*)py_malloc(sizeof(py_code_object));
    code->obj.type = PY_TYPE_NONE; /* 代码对象没有特定的类型 */
    code->obj.ref_count = 1;
    code->obj.next = NULL;
    
    code->arg_count = 0;
    code->local_count = 0;
    code->stack_size = 100;
    code->flags = 0;
    code->name = strdup("__main__");
    code->filename = strdup(filename);
    code->first_lineno = 1;
    code->consts = (py_object*)py_tuple_new(0);
    code->names = (py_object*)py_tuple_new(0);
    code->locals = (py_object*)py_tuple_new(0);
    code->freevars = (py_object*)py_tuple_new(0);
    code->cellvars = (py_object*)py_tuple_new(0);
    code->code = NULL;
    code->code_length = 0;
    code->lnotab = (py_object*)py_tuple_new(0);
    
    /* 非常简单的解析器，只能处理print语句 */
    if (strncmp(source, "print", 5) == 0) {
        const char* p = source + 5;
        while (*p && isspace(*p)) p++;
        
        if (*p == '(') {
            p++;
            while (*p && isspace(*p)) p++;
            
            if (*p == ')') {
                /* print() */
                code->code = (unsigned char*)py_malloc(3);
                code->code_length = 3;
                code->code[0] = OP_LOAD_GLOBAL;
                code->code[1] = 0;
                code->code[2] = 0;
                code->code[3] = OP_CALL_FUNCTION;
                code->code[4] = 0;
                code->code[5] = 0;
                code->code[6] = OP_POP_TOP;
            } else if (*p == '"' || *p == '\'') {
                /* print("string") */
                char quote = *p;
                p++;
                const char* start = p;
                while (*p && *p != quote) p++;
                
                if (*p == quote) {
                    size_t len = p - start;
                    char* str = (char*)py_malloc(len + 1);
                    memcpy(str, start, len);
                    str[len] = '\0';
                    
                    /* 添加字符串常量 */
                    py_tuple_object* consts = (py_tuple_object*)code->consts;
                    consts->items = (py_object**)py_realloc(consts->items, sizeof(py_object*) * (consts->length + 1));
                    consts->items[consts->length++] = py_string_new(str);
                    py_free(str);
                    
                    /* 添加名称 */
                    py_tuple_object* names = (py_tuple_object*)code->names;
                    names->items = (py_object**)py_realloc(names->items, sizeof(py_object*) * (names->length + 1));
                    names->items[names->length++] = py_string_new("print");
                    
                    /* 生成字节码 */
                    code->code = (unsigned char*)py_malloc(9);
                    code->code_length = 9;
                    code->code[0] = OP_LOAD_CONST;
                    code->code[1] = 0;
                    code->code[2] = 0;
                    code->code[3] = OP_LOAD_GLOBAL;
                    code->code[4] = 0;
                    code->code[5] = 0;
                    code->code[6] = OP_CALL_FUNCTION;
                    code->code[7] = 1;
                    code->code[8] = 0;
                    code->code[9] = OP_POP_TOP;
                }
            }
        }
    }
    
    return code;
}

/* 主函数 */
int main(int argc, char** argv) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <python file>\n", argv[0]);
        return 1;
    }
    
    /* 读取Python文件 */
    FILE* file = fopen(argv[1], "r");
    if (!file) {
        fprintf(stderr, "Cannot open file: %s\n", argv[1]);
        return 1;
    }
    
    fseek(file, 0, SEEK_END);
    long size = ftell(file);
    fseek(file, 0, SEEK_SET);
    
    char* source = (char*)py_malloc(size + 1);
    fread(source, 1, size, file);
    source[size] = '\0';
    fclose(file);
    
    /* 创建虚拟机 */
    py_vm* vm = py_vm_new();
    
    /* 编译并执行代码 */
    py_code_object* code = py_compile(source, argv[1], 0);
    py_object* result = py_vm_run(vm, code);
    
    /* 清理资源 */
    py_object_decref(result);
    py_object_decref((py_object*)code);
    py_free(source);
    py_vm_free(vm);
    
    return 0;
}